﻿using System.Drawing;
using System;

namespace Yelper.Web.Helpers {

    public static class ImageHelper {

        public static void ResizeImageIfTooWide(string file, string target, int width) {
            Image original = Image.FromFile(file);
            if (original.Width > width) {
                float aspect = (float)original.Height / (float)original.Width;
                int height = (int)(width * aspect);
                Image result = new Bitmap(width, height);
                Graphics g = Graphics.FromImage(result);
                g.DrawImage(original, 0, 0, width, height);
                g.Flush();
                result.Save(target, original.RawFormat);
                g.Dispose();
                result.Dispose();
            } else {
                original.Save(target, original.RawFormat);
            }
            original.Dispose();
        }

        public static void CropAndResizeTo80(string file, string target, int x, int y, int w, int h) {
            Image original = Image.FromFile(file);

            Image result = new Bitmap(80, 80);
            Graphics g_result = Graphics.FromImage(result);

            if (0 != w && 0 != h) {

                Image temp = new Bitmap(w, h);
                Graphics g_temp = Graphics.FromImage(temp);
                
                g_temp.DrawImage(original, -x, -y, original.Width, original.Height);
                g_result.DrawImage(temp, 0, 0, 80, 80);

                g_temp.Dispose();
                temp.Dispose();

            } else {

                g_result.DrawImage(original, 0, 0, 80, 80);
               
            }

            result.Save(target);

            original.Dispose();
            g_result.Dispose();
            result.Dispose();
        }

    }

}